<template>
  <div class="container">
    <div class="login-wrapper">
      <div class="header">Login</div>
      <div class="form-wrapper">
        <el-form :rules="hospitalrules" ref="formRef" :model="loginObj">
          <el-form-item prop="username">
            <div class="input-item">
              <el-input type="text" name="username" placeholder="username" v-model="loginObj.username" />
            </div>
          </el-form-item>
          <el-form-item prop="password">
            <div class="input-item">
              <el-input type="password" name="password" placeholder="password" v-model="loginObj.password" />
            </div>
          </el-form-item>


          <div class="box">
            <div class="input-item">
              <el-row type="flex" justify="space-between" align="middle">
                <el-col :span="11">
                  <el-input type="text" v-model="loginObj.captcha" placeholder="请输入验证码" />
                </el-col>
                <div class="gap" style="width: 2%;"></div>
                <el-col :span="11" :offset="1">
                  <el-image :src="captchaUrl" style="cursor: pointer;" @click="handleCaptcha"></el-image>

                </el-col>
              </el-row>
              <div class="check-code-display" @click="createCode">{{ checkCode }}</div>
            </div>
          </div>

          <div class="remember-me">
            <input type="checkbox" v-model="rememberMe" /> 记住我
          </div>
        
          <div class="btn" @click="dologin()">登录</div>
          <div class="btn">
            <router-link to="/register" class="btn-link">注册</router-link>
          </div>
        </el-form>


      </div>
    </div>


  </div>
</template>






<script setup>
  import {
    reactive,
    ref
  } from 'vue'
  import loginapi from '../api'
  import {
    useRoute,
    useRouter
  } from 'vue-router'
  import {
    ElMessageBox,
    ElMessage
  } from 'element-plus';
  import {
    onMounted
  } from 'vue';
  import * as auth from '../util/auth'



  const captchaUrl = ref("/api/captcha");
  const router = useRouter();
  const formRef = ref({});
  const loginObj = reactive({
    username: '',
    password: '',
    captcha: ''
  })
  const rememberMe = ref(false)
  const checkCode = ref('')

  const dologin = async function () {
    formRef.value.validate(async (valid) => {
      if (!valid) {
        console.log('error submit!')
        return
      }



      let result = await loginapi.postJson("/api/dologin", loginObj);

      if (result.code == 200 && result.data) {
        // 登陆成功
        // 存放token
        auth.setToken(result.data)
        console.log(auth.getToken())
        //console.log(result.data)
        // 提示
        ElMessage({
          type: 'success',
          message: result.message,
        });

        setTimeout(function () {
          router.push("/hospital");
        }, 1000)
        //console.log(result.data)
        // 保存用户名和密码到 localStorage
        if (rememberMe.value) {
          // 使用 auth.js 中的 saveUserInfo 函数
          auth.saveUserInfo(loginObj.username, loginObj.password,rememberMe.value)
        } else {
          // 使用 auth.js 中的 clearUserInfo 函数
          auth.clearUserInfo()
        }
        


      }else {
          ElMessage({
            type: 'error',
            message: '登录失败,请检查您的用户名和密码'
          })

          return
        }
    })
  }
  const checkname = function (rule, value, callback) {
    let reg = /^[1-9]\d*$/;

    if (reg.test(value)) {
      callback();
    } else {
      callback(new Error('用户格式不正确'))

    }
  }
  const hospitalrules = {
    username: [{
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
      },
      {
        validator: checkname,
        trigger: 'blur'
      }
    ],
    password: [{
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }],
    captcha: [{
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    }]
  }

  onMounted(() => {
    // 在组件挂载时检查是否有保存的用户名和密码
    const savedUserInfo = auth.getUserInfo() // 使用 auth.js 中的 getUserInfo 函数获取用户信息
    if (savedUserInfo) {
      loginObj.username = savedUserInfo.username
      loginObj.password = savedUserInfo.password
      // 读取 localStorage 中的 rememberMe 状态
      rememberMe.value = localStorage.getItem('rememberMe') === 'true' // 设置 rememberMe 为 true
    }


  })

function handleCaptcha(){
  captchaUrl.value='api/captcha?'+new Date().getTime();
}


</script>

<style>
  html {
    height: 100%;
  }

  body {
    height: 100%;
  }

  .container {
    /* margin-top: 5%; */
    height: 980px;
    width: 100%;
    background-image: url('./login-bg.jpg');
    background-blend-mode: multiply;
    background-repeat: no-repeat;
    background-position: center;
    background-attachment: fixed;
    background-size: cover;
  }

  .login-wrapper {
    background-color: #fff;
    width: 358px;
    height: 688px;
    border-radius: 15px;
    padding: 0 50px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

  }

  .header {
    font-size: 38px;
    font-weight: bold;
    text-align: center;
    line-height: 200px;
  }

  .input-item {
    display: block;
    width: 100%;
    margin-bottom: 20px;
    border: 0;
    padding: 10px;
    border-bottom: 1px solid rgb(128, 125, 125);
    font-size: 15px;
    outline: none;
  }

  .input-item:placeholder {
    text-transform: uppercase;
  }

  .btn {
    text-align: center;
    padding: 10px;
    margin: 0 auto;
    width: 100%;
    margin-top: 30px;
    background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
    color: #fff;
    
  }

  .msg {
    text-align: center;
    line-height: 88px;
  }

  a {
    text-decoration-line: none;
    color: #abc1ee;
  }

  /* 验证码 */
  .code-wrapper {
    display: flex;
    align-items: center;
  }

  .input-item {
    flex: 1;
    margin-right: 10px;
    /* 验证码输入框与显示区之间的间隔 */
  }

  .checkCode {
    cursor: pointer;
    user-select: none;
    padding: 10px;
    border: 1px solid #ccc;
    /* 验证码显示区边框 */
    /* 其他样式... */
  }

  /* 添加媒体查询以适应不同屏幕尺寸 */
  @media (max-width: 600px) {
    .code-wrapper {
      flex-direction: column;
      align-items: stretch;
    }

  
    .checkCode {
      margin-right: 0;
      margin-bottom: 10px;
    }
  }

  .remember-me {
    display: flex;
    justify-content: space-between;
    /* 对齐项 */
    align-items: center;
  }

  .gap {
    width: 10px;
    /* 可以根据需要调整间隙大小 */
    height: 100%;
    background-color: transparent;
    /* 根据需要调整，可以设置背景色 */
  }
</style>